<template>
	<view class="container">
		<!--收货地址.开始-->
		<view class="group-box">
			<navigator v-if="!useAddress" url="../account/address/list?source=1" class="address-add">
				<text class="icon iconfont icon-add"></text>
				<text class="text">新增收货地址</text>
			</navigator>
			<navigator v-else url="../account/address/list?source=1" class="address-box">
				<view class="icon iconfont icon-address"></view>
				<view class="item">
					<view class="contact">
						<text class="name">{{useAddress.acceptName}}</text>
						<text class="tel">{{useAddress.mobile}}</text>
					</view>
					<view class="detail">{{useAddress.address}}</view>
				</view>
			</navigator>
		</view>
		<!--收货地址.结束-->

		<!--商品列表.开始-->
		<view class="group-box wrap">
			<view class="cart-list">
				<view v-for="(item, index) in cartTotal.list" :key="index" class="list-wrap">
					<view class="list-head">
						<view class="left">
							<navigator :url="'../merchant/index?id='+item.merchantId" class="title">
								<text class="label" v-if="item.isSelf==1">自营</text>
								<text>{{item.merchantTitle}}</text>
							</navigator>
						</view>
					</view>
					<view v-for="(gitem, gindex) in item.goods" :key="gindex" class="list-box">
						<view class="left">
							<view class="img-box">
								<image mode="widthFix" :src="$api.loadFile(gitem.imgUrl)"></image>
							</view>
						</view>
						<view class="right">
							<text class="title">{{gitem.title}}</text>
							<text class="attr">{{gitem.skuText}}</text>
							<view class="num-box">
								<text class="price">{{gitem.groupPrice}}</text>
								<text class="number">x {{gitem.quantity}}</text>
							</view>
						</view>
					</view>
					<view class="list-foot">
						<view class="item-box" @click="openTicket(item)" v-if="orderType==0&&item.shopCoupons.length>0">
							<text class="title">优惠券</text>
							<text class="remark opt">
								{{item.couponTitle?item.couponTitle:'选择优惠券'}}
							</text>
						</view>
						<view class="item-box" @click="openDelivery(item)">
							<text class="title">配&nbsp;&nbsp;&nbsp;&nbsp;送</text>
							<text class="remark opt">
								{{item.deliveryTitle?item.deliveryTitle+(item.freightAmount>0?' (运费'+item.freightAmount+'元)':' (免运费)'):'选择配送方式'}}
							</text>
						</view>
						<view class="item-box">
							<text class="title">备&nbsp;&nbsp;&nbsp;&nbsp;注</text>
							<view class="remark">
								<input v-model="item.postscript" class="input" type="text" placeholder="选项，订单备注留言" />
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!--商品列表.结束-->

		<!--选项.开始-->
		<view class="group-box top-0">
			<view class="item-list">
				<view class="list-box" @click="$refs.popPayment.open()">
					<text class="title">支付方式</text>
					<text class="remark opt">
						{{usePayment.title?usePayment.title:'选择付款方式'}}
					</text>
				</view>

				<view v-if="orderType<3" class="list-box">
					<text class="title">商品金额</text>
					<text class="remark right">￥{{cartTotal.totalRealAmount}} 元</text>
				</view>
				<view v-if="orderType===3" class="list-box">
					<text class="title">兑换积分</text>
					<view class="remark right">
						<text class="price">- {{cartTotal.totalPoint}} 分</text>
					</view>
				</view>
				<view class="list-box" v-if="cartTotal.totalFreightAmount>0">
					<text class="title">总&nbsp;&nbsp;运&nbsp;&nbsp;费</text>
					<view class="remark right">
						<text class="price">+￥{{cartTotal.totalFreightAmount}} 元</text>
					</view>
				</view>
				<view class="list-box" v-if="cartTotal.totalCouponAmount>0">
					<text class="title">优惠券抵</text>
					<view class="remark right">
						<text class="price">-￥{{cartTotal.totalCouponAmount}} 元</text>
					</view>
				</view>
				<view class="list-box" v-if="cartTotal.totalPromotionAmount>0">
					<text class="title">活动促销</text>
					<view class="remark right">
						<text class="price">-￥{{cartTotal.totalPromotionAmount}} 元</text>
					</view>
				</view>
			</view>
		</view>
		<!--选项.结束-->

		<!--底部按钮.开始-->
		<view class="foot-wrap">
			<view class="foot-box">
				<view class="left">
					<text v-if="orderType==2">预售定金</text>
					<text v-else>实付款</text>
					<text class="price">{{cartTotal.totalOrderAmount}} 元</text>
				</view>
				<view class="right">
					<text @click="saveOrder" class="btn-submit">提交订单</text>
				</view>
			</view>
		</view>
		<!--底部按钮.结束-->

		<!--优惠券.开始-->
		<uni-popup ref="popTicket" type="bottom" @change="changeTicket">
			<view class="goods-ticket">
				<view class="head-box">
					<view class="stitle">
						<text class="title">可用优惠券</text>
					</view>
				</view>
				<scroll-view scroll-y class="list-wrap">
					<view v-for="(item,index) in currTotalList.shopCoupons" :key="index" class="list-box">
						<view class="left">
							<text class="price">{{item.amount}}</text>
						</view>
						<view class="center">
							<view class="title">
								<text class="label" v-if="item.useType==1">商品券</text>
								<text class="label" v-else>店铺券</text>
								<text>{{item.title}}</text>
							</view>
							<text class="time">有效期至{{item.endTime}}</text>
						</view>
						<view class="right">
							<label @click="selectTicket(item)">
								<radio color="#fa436a" :checked="item.id==currTotalList.couponId" />
								</radio>
							</label>
						</view>
					</view>
				</scroll-view>
				<view class="foot-box">
					<button @click="$refs.popTicket.close()" class="btn">确定</button>
				</view>
			</view>
		</uni-popup>
		<!--优惠券.结束-->

		<!--配送方式.开始-->
		<uni-popup ref="popDelivery" type="bottom" @change="changeDelivery">
			<view class="popup-item-box">
				<view class="head-box">
					<view class="stitle">
						<text class="title">配送方式</text>
					</view>
				</view>
				<scroll-view scroll-y class="list-wrap">
					<view v-for="(item,index) in currTotalList.shopDeliverys" :key="index" @click="selectDelivery(item)"
						:class="{active: item.id==currTotalList.deliveryId}" class="list-box">
						<text class="text">{{item.title}}</text>
						<label class="radio">
							<radio color="#fa436a" :checked="item.id==currTotalList.deliveryId" />
							</radio>
						</label>
					</view>
				</scroll-view>
				<view class="foot-box">
					<button @click="$refs.popDelivery.close()" class="btn">确定</button>
				</view>
			</view>
		</uni-popup>
		<!--配送方式.结束-->

		<!--支付方式.开始-->
		<uni-popup ref="popPayment" type="bottom">
			<view class="popup-item-box">
				<view class="head-box">
					<view class="stitle">
						<text class="title">付款方式</text>
					</view>
				</view>
				<scroll-view scroll-y class="list-wrap">
					<view v-for="(item,index) in paymentList" :key="index" @click="selectPayment(item)"
						:class="{active: usePayment.id&&usePayment.id===item.id}" class="list-box">
						<text class="text">{{item.title}}</text>
						<label class="radio">
							<radio color="#fa436a" :checked="usePayment.id&&usePayment.id===item.id" />
							</radio>
						</label>
					</view>
				</scroll-view>
				<view class="foot-box">
					<button @click="$refs.popPayment.close()" class="btn">确定</button>
				</view>
			</view>
		</uni-popup>
		<!--支付方式.结束-->

	</view>
</template>

<script>
	export default {
		data() {
			return {
				orderType: 0, //订单类型
				activeId: 0, //订单类型为1时抢购ID，为2时换购ID
				currTotalList: {}, //当前编辑行
				goodsData: null, //普通订单的货品传参
				useAddress: null, //收货地址
				usePayment: {}, //已选支付方式
				cartTotal: {}, //统计列表
				couponList: [], //购物券列表
				deliveryList: [], //配送列表
				paymentList: [], //支付列表
			}
		},
		methods: {
			//初始化数据
			async initData() {
				let _this = this;
				//正在加载
				uni.showLoading({
					title: '加载中'
				});
				//如果是普通订单
				if (_this.orderType === 0) {
					//加载商品列表
					await _this.$api.request({
						url: `/account/shop/cart/buy?jsonData=${_this.goodsData}`,
					}).then(res => {
						//console.log(res.data)
						_this.cartTotal = res.data;
					});
				}
				//抢购商品
				else if (_this.orderType === 1) {
					//加载商品列表
					await _this.$api.request({
						url: `/account/shop/speed/buy/${_this.activeId}`,
					}).then(res => {
						//console.log(res.data)
						_this.cartTotal = res.data;
					});
				}
				//预售商品
				else if (_this.orderType === 2) {
					//加载商品列表
					await _this.$api.request({
						url: `/account/shop/presell/buy/${_this.activeId}`,
					}).then(res => {
						//console.log(res.data)
						_this.cartTotal = res.data;
					});
				}
				//积分换购
				else if (_this.orderType === 3) {
					//加载商品列表
					await _this.$api.request({
						url: `/account/shop/convert/buy/${_this.activeId}`,
					}).then(res => {
						//console.log(res.data)
						_this.cartTotal = res.data;
					});
				}

				//根据环境加载支付列表
				let sendUrl = `/client/payment/view/10`;
				//#ifdef APP-PLUS
				sendUrl += `?types=cash,balance,app`;
				//#endif
				//#ifdef H5
				//判断是否在微信浏览器里打开
				let ua = window.navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == 'micromessenger') {
					sendUrl += `?types=cash,balance,jsapi`;
				} else {
					sendUrl += `?types=cash,balance,h5`;
				}
				//#endif
				//#ifdef MP
				sendUrl += `?types=cash,balance,mp`;
				//#endif
				await _this.$api.request({
					url: sendUrl,
				}).then(res => {
					//console.log(res.data)
					_this.paymentList = res.data;
				});
				//加载收货地址
				await _this.$api.request({
					url: `/account/member/address`,
				}).then(res => {
					_this.useAddress = res.data;
				}).catch(err => {});
				//关闭加载
				uni.hideLoading();
			},
			//统计订单金额
			totalAmount() {
				let _this = this;
				let totalFreightAmount = 0;
				let totalCouponAmount = 0;
				_this.cartTotal.list.forEach(item => {
					totalFreightAmount += item.freightAmount;
					totalCouponAmount += item.couponAmount;
				});
				_this.cartTotal.totalFreightAmount = totalFreightAmount;
				_this.cartTotal.totalCouponAmount = totalCouponAmount;
				//如果不是预售订单则需要计算总费用
				if (_this.orderType != 2) {
					//订单总金额=商品实付金额-促销金额-优惠券金额+运费
					_this.cartTotal.totalOrderAmount = (parseFloat(_this.cartTotal.totalRealAmount) - parseFloat(_this
						.cartTotal.totalPromotionAmount) - parseFloat(totalCouponAmount) + parseFloat(
						totalFreightAmount)).toFixed(2);

					// if (_this.cartTotal.totalOrderAmount < 0) {
					// 	_this.cartTotal.totalOrderAmount = 0;
					// }
				}
			},
			//打开优惠券弹窗
			openTicket(val) {
				this.$refs.popTicket.open();
				this.currTotalList = val;
			},
			//关闭优惠券窗口回调
			changeTicket() {
				this.currTotalList = {};
			},
			//选择优惠券
			selectTicket(val) {
				this.currTotalList.couponId = val.id;
				this.currTotalList.couponAmount = val.amount;
				this.currTotalList.couponTitle = val.title;
				//重新统计
				this.totalAmount();
				this.$refs.popTicket.close();
			},
			//打开配送弹窗
			openDelivery(val) {
				this.$refs.popDelivery.open();
				this.currTotalList = val;
			},
			//关闭配送窗口回调
			changeDelivery() {
				this.currTotalList = {};
			},
			//选择配送方式
			selectDelivery(item) {
				let _this = this;
				//检查是否选择了地址
				if (!_this.useAddress || !_this.useAddress.province) {
					uni.showModal({
						title: '提示',
						content: '请先选择收货地址',
						showCancel: false
					});
					return;
				}
				this.currTotalList.deliveryId = item.id;
				this.currTotalList.deliveryTitle = item.title;
				//计算配送费用,如果商品全免运费则配送费为0
				if ((this.currTotalList.promotion && this.currTotalList.promotion.awardType == 6) || this.currTotalList
					.freeFreight == 1) {
					this.currTotalList.freightAmount = 0;
				} else {
					//计算配送费用
					let totalWeight = this.currTotalList.totalWeight > 1000 ? Math.ceil(this.currTotalList.totalWeight /
						1000) : 1;
					let firstPrice = item.firstPrice; //首重费用
					let secondPrice = item.secondPrice; //续重费用
					let totalSecondPrice = 0; //续重总费用
					//查询是否是设置了个别地区
					let areaObj = item.deliveryAreas.find(val => val.province == _this.useAddress.province);
					if (areaObj) {
						firstPrice = areaObj.firstPrice;
						secondPrice = areaObj.secondPrice;
					}
					//如果总重量大于首重才计算续重费用
					if (totalWeight > item.firstWeight) {
						//续重重量=总重量-首重量
						let secondWeight = totalWeight - item.firstWeight;
						//向上取整，只要有小数都加1
						//续重费用=(续重重量/续重量)*续重价格
						totalSecondPrice = Math.ceil(secondWeight / item.secondWeight) * secondPrice;
					}
					//总运费=首重费用+续重费用+保价费用
					this.currTotalList.freightAmount = firstPrice + totalSecondPrice;
				}
				//重新统计
				_this.totalAmount();
				this.$refs.popDelivery.close();
			},
			//选择支付方式
			selectPayment(item) {
				let _this = this;
				_this.usePayment = item;
				_this.$refs.popPayment.close();
			},
			//保存订单
			async saveOrder() {
				let _this = this;
				//检查收货地址
				if (!_this.useAddress) {
					_this.$api.msg("请选择收货地址");
					return false;
				}
				//检查支付方式
				if (!_this.usePayment.id) {
					_this.$api.msg("请选择支付方式");
					return false;
				}
				//检查配送方式
				// if(!!_this.cartTotal.list.find(val=>val.deliveryId==0)){
				// 	_this.$api.msg("请选择配送方式");
				// 	return false;
				// }
				//检查商品列表
				if (!_this.cartTotal.list) {
					_this.$api.msg("结算商品不能为空")
					return false;
				}

				//开始保存订单
				let model = {};
				model.orderType = _this.orderType; //0普通订单1抢购订单2换购订单
				model.activeId = _this.activeId; //抢购ID或换购ID
				model.paymentId = _this.usePayment.id;
				model.acceptName = _this.useAddress.acceptName;
				model.mobile = _this.useAddress.mobile;
				model.province = _this.useAddress.province;
				model.city = _this.useAddress.city;
				model.area = _this.useAddress.area;
				model.address = _this.useAddress.address;
				model.orderList = [];
				//循环列表
				_this.cartTotal.list.forEach(item => {
					let modelt = {};
					let orderGoods = [];
					modelt.merchantId = item.merchantId;
					modelt.activeId = _this.activeId;
					modelt.deliveryId = item.deliveryId;
					modelt.useCouponId = item.couponId;
					modelt.isInsure = 0;
					modelt.insurePrice = 0;
					modelt.postscript = item.postscript;
					//modelt.acceptTime = item.acceptTime;
					item.goods.forEach(gitem => {
						orderGoods.push({
							productId: gitem.productId,
							quantity: gitem.quantity
						});
					});
					modelt.orderGoods = orderGoods;
					//添加进订单列表
					model.orderList.push(modelt);
				});
				//提交订单
				await _this.$api.request({
					url: `/account/order`,
					method: "post",
					data: model,
					loading: true
				}).then(res => {
					//判断配送方式是否线下支付
					if (_this.usePayment.providerType == 0) {
						uni.showModal({
							title: "订单提交成功",
							content: '是否查看订单详情？',
							cancelText: '继续购物',
							confirmText: '查看订单',
							success(e) {
								if (e.cancel) {
									uni.switchTab({
										url: '../goods/index'
									})
								} else if (e.confirm) {
									uni.redirectTo({
										url: `list`
									});
								}
							}
						});
					} else {
						uni.navigateTo({
							url: `../payment/confirm?no=${res.data.tradeNo}`
						});
					}
				}).catch(err => {
					console.log(err);
				})
			}
		},
		onLoad(options) {
			this.orderType = parseInt(options.type);
			if (this.orderType > 0) {
				//抢购预售换购订单
				this.activeId = parseInt(options.id);
			} else {
				//普通订单
				this.goodsData = options.data;
			}
			//初始化数据
			this.initData();
		}
	}
</script>

<style lang="scss">
	.address-add {
		display: flex;
		justify-content: center;
		color: #666;
		font-size: 30rpx;
		align-items: center;
		background: #fff;
		border-radius: 20rpx;
		height: 86rpx;

		.icon {
			margin-right: 10rpx;
			color: #f63434;
		}

		.text {}
	}

	.address-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx;
		border-radius: 20rpx;
		background: #fff;

		.icon {
			display: flex;
			align-items: center;
			color: #888;
			font-size: 48rpx;
			line-height: 1;
			width: 72rpx;
		}

		.item {
			flex-grow: 1;
			position: relative;
			padding-right: 32rpx;
			line-height: 1;

			.contact {
				display: block;

				.name {
					color: #333;
					font-size: 30rpx;
				}

				.tel {
					margin-left: 10rpx;
					color: #666;
					font-size: 28rpx;
				}
			}

			.detail {
				display: block;
				padding-top: 12rpx;
				color: #999;
				font-size: 26rpx;
				line-height: 36rpx;
			}

			&::after {
				color: #999;
				font-size: 28rpx !important;
				font-family: "iconfont";
				content: "\e68d";
				position: absolute;
				top: 50%;
				right: 0;
				margin-top: -14rpx;
				width: 28rpx;
				height: 28rpx;
				line-height: 1;
			}
		}
	}

	.popup-item-box {
		box-sizing: border-box;
		padding: 24rpx;
		background: #fff;
		border-radius: 20rpx 20rpx 0 0;

		.list-wrap {
			margin: 0 0 40rpx;
			max-height: calc(100vh - 450rpx);

			.list-box {
				display: flex;
				justify-content: space-between;
				align-items: center;
				position: relative;
				box-sizing: border-box;
				margin-top: 24rpx;
				padding: 20rpx 24rpx;
				border: 2rpx solid #f5f5f5;
				border-radius: 20rpx;
				background: #f5f5f5;
				color: #333;
				font-size: 26rpx;

				&.active {
					border-color: rgba($color: #f63434, $alpha: 0.6);
					background: #fff;
				}

				.text {}

				.radio {}
			}
		}

		.foot-box {
			.btn {
				padding: 24rpx 30rpx;
				color: #fff;
				font-size: 28rpx;
				line-height: 1;
				border-radius: 50rpx;
				background: #ff5000;

				&::after {
					border: none;
				}
			}
		}
	}

	.foot-wrap {
		height: 96rpx;

		.foot-box {
			display: flex;
			justify-content: space-between;
			align-items: center;
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			padding: 0 24rpx;
			height: 100rpx;
			box-shadow: 0 -2rpx 8rpx rgba($color: #000, $alpha: 0.05);
			background: #fff;

			.left {
				color: #666;
				font-size: 30rpx;
				line-height: 1;

				.price {
					margin-left: 6rpx;
					color: #fa436a;
					font-size: 36rpx;

					&::before {
						content: "￥";
						font-size: 28rpx;
					}
				}
			}

			.right {
				.btn-submit {
					display: block;
					padding: 0 48rpx;
					color: #fff;
					font-size: 30rpx;
					line-height: 76rpx;
					height: 76rpx;
					background: #ff5000;
					border-radius: 76rpx;
				}
			}
		}
	}
</style>